<template>
    <div>
        <!-- 版心 -->
        <div class="container">
            <!-- 标题 -->
            <div class="title row">
                <span class="tag">标题: </span>
                <el-input placeholder="请输入标题（最多 60 字）" clearable maxlength="60" show-word-limit v-model="article.title">
                </el-input>
            </div>
            <!-- 描述 -->
            <div class="row">
                <span class="tag">描述: </span>
                <el-input placeholder="请简单的介绍一下内容吧~（最多 128 字）" clearable maxlength="128" show-word-limit
                    v-model="article.desc"></el-input>
            </div>
            <!-- 内容 -->
            <div class="content">
                <span class="tag">内容: </span>
                <!-- markdown 语法编译器 -->
                <mavon-editor ref="md" v-model="article.content" placeholder="请输入内容" :ishljs="true" @imgAdd="imgAdd" />
            </div>
            <!-- 文章分类 -->
            <div class="classify row">
                <span class="tag">分类: </span>
                <!-- TODO -->
                <div class="radio" v-for="(board, index) in boards" :key="board">
                    <el-button plain @click="onBoard(board)">{{ board }}</el-button>
                </div>
            </div>
            <!-- TODO封面(暂不开发) -->
            <!-- <div></div> -->
            <!-- 提交与保存 -->
            <div class="button">
                <span class="tag"></span>
                <el-button class="publish" type="primary" @click="publish()">发布</el-button>
                <el-button class="save">存入草稿箱</el-button>
            </div>
        </div>
    </div>
</template>

<script>
import instance from "../../utils/request"
import { Message } from "element-ui"

//引入 markDown 编译器
export default {
    name: "Publish",
    data() {
        return {
            //文章内容
            article: {
                userId: -1,
                title: "",     //标题
                desc: "",      //描述
                content: "",   //内容
                board: ""      //板块
            },
            //文章分类(从后端数据库中拿)
            boards: [],
        }
    },
    methods: {
        /**
         * 选中的板块
         * @param {} board 板块名
         */
        onBoard(board) {
            this.article.board = board;
        },
        /**
         * 发布文章
         */
        publish() {
            //1.非空校验
            if (this.article.title == null || this.article.title == '') {
                Message.warning("标题不能为空！");
                return;
            }
            if (this.article.desc == null || this.article.desc == '') {
                Message.warning("描述不能为空！");
                return;
            }
            if (this.article.content == null || this.article.content == '') {
                Message.warning("内容不能为空！");
                return;
            }
            //获取作者id
            this.article.userId = localStorage.getItem("id");
            //2.发布文章
            instance.post("/article/publish", this.article).then(success => {
                if (success.data.code == 1000) {
                    Message.success("文章发布成功！");
                    this.$router.push({name: 'Personal'}) //发布成功后跳转到个人首页
                }
            }).catch(error => {
                    Message.error("文章发布失败!")
                    console.log(error)
            });
        },
        /**
         * 添加照片
         * 绑定@imgAdd event
         * @param {*} pos 
         * @param {*} $file 
         */
        imgAdd(pos, $file) {
            // console.log(pos,$file);
            let $vm = this.$refs.md
            // 第一步.将图片上传到服务器.
            const formdata = new FormData();
            formdata.append('image', $file);
            // this.$axios.post(`${this.api}/file/upload`,{
            this.request.post(`/file/upload`, {
                data: formdata,
                headers: { 'Content-Type': 'multipart/form-data' }
            }).then((res) => {
                // 第二步.将返回的url替换到文本原位置![...](./0) -> ![...](url)
                // console.log(res);
                $vm.$img2Url(pos, res.data.data);
            })
        },
    },
    created() {
        //获取板块数据
        instance.get("/article/boards").then(success => {
            if (success.data.code == 1000) {
                this.boards = success.data.data;
                //去掉最新(数组第一个元素)
                this.boards.shift();
               } else {
                Message.error("板块数据获取错误，请稍后重试");
                console.log(success.data);
            }
        }).catch(error => {
            Message.error("板块数据获取异常，请稍后重试");
            console.log(error);
        });
    }

}
</script>

<style scoped>
.container {
    width: 1200px;
    height: 700px;
    margin: 30px auto;
    background-color: white;
    padding: 30px;
}

.container .row {
    height: 60px;
    width: 1140px;
    display: flex;
    justify-content: left;
    margin: 10px 0;
}


.container .tag {
    width: 45px;
    margin-right: 100px;
}

.container .content {
    width: 1140px;
    height: 320px;
    display: flex;
    justify-content: left;
    margin: 10px 0;
}

.container .button {
    width: 500px;
    padding: 10px 10px;
    display: flex;
    justify-content: left;
}

.container .publish {
    width: 300px;
}

.classify {
    display: flex;
    align-items: center;
}

.radio {
    display: flex;
    align-items: center;
}
</style>